# Ensure ImportExcel module is installed if (-not (Get-Module -ListAvailable -Name ImportExcel)) { Write-Host "๐Ÿ“ฆ ImportExcel module not found. Installing..." Install-Module -Name ImportExcel -Scope CurrentUser -Force } else { Write-Host "โœ… ImportExcel module is already installed." } # Ensure ExchangeOnlineManagement module is installed if (-not (Get-Module -ListAvailable -Name ExchangeOnlineManagement)) { Write-Host "๐Ÿ“ฆ ExchangeOnlineManagement module not found. Installing..." Install-Module -Name ExchangeOnlineManagement -Scope CurrentUser -Force } else { Write-Host "โœ… ExchangeOnlineManagement module is already installed." } # Output Excel file path $excelPath = "C:\Temp\DeviceAccessReport.xlsx" # Ensure C:\Temp exists if (!(Test-Path -Path "C:\Temp")) { New-Item -Path "C:\" -Name "Temp" -ItemType Directory | Out-Null } # Connect to Exchange Online Connect-ExchangeOnline # Get all user mailboxes $mailboxes = Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails UserMailbox # Store device stats $deviceStats = @() foreach ($mbx in $mailboxes) { try { $stats = Get-MobileDeviceStatistics -Mailbox $mbx.Identity -ErrorAction Stop foreach ($stat in $stats) { $deviceStats += [PSCustomObject]@{ User = $mbx.DisplayName DeviceID = $stat.DeviceID DeviceType = $stat.DeviceType DeviceModel = $stat.DeviceModel OS = $stat.DeviceOS ClientType = $stat.ClientType AccessState = $stat.DeviceAccessState AccessReason = $stat.DeviceAccessStateReason LastSuccessSync = $stat.LastSuccessSync FirstSyncTime = $stat.FirstSyncTime } } } catch { Write-Warning "โš ๏ธ Failed to get device stats for $($mbx.DisplayName): $_" } } # Export to Excel $deviceStats | Export-Excel -Path $excelPath -AutoSize -WorksheetName "Device Access" Write-Host "`nโœ… Report exported to $excelPath" # Disconnect from Exchange Online Disconnect-ExchangeOnline -Confirm:$false # Clear cached credentials to force reauthentication next time Remove-Item "$env:USERPROFILE\.ExchangeOnline\TokenCache" -Force -ErrorAction SilentlyContinue Write-Host "`n๐Ÿงน Cached credentials cleared. Reauthentication will be required on next run."